import os

from sklearn.cluster import KMeans
import sys

sys.path.append('..')
from utils.log import Logger

os.environ['OMP_NUM_THREADS'] = '2'
import pandas as pd
import joblib
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.metrics import precision_score, recall_score, f1_score
from sklearn.preprocessing import StandardScaler
from sklearn.utils import class_weight
import datetime

# 数据处理&特征删除&特征热编码
def Data_process(data):
    feature = ['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome',
               'Education', 'EducationField', 'EmployeeNumber',
               'EnvironmentSatisfaction', 'Gender', 'JobInvolvement', 'JobLevel',
               'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome',
               'NumCompaniesWorked', 'Over18', 'OverTime', 'PercentSalaryHike',
               'PerformanceRating', 'RelationshipSatisfaction', 'StandardHours',
               'StockOptionLevel', 'TotalWorkingYears', 'TrainingTimesLastYear',
               'WorkLifeBalance', 'YearsAtCompany', 'YearsInCurrentRole',
               'YearsSinceLastPromotion', 'YearsWithCurrManager']
    enc = joblib.load('../model/OneHot_enc.pkl')
    ret_data = data.copy(deep=True)
    ret_data.drop(
        ['Over18', 'NumCompaniesWorked', 'PercentSalaryHike', 'TrainingTimesLastYear', 'EmployeeNumber', 'Education',
         'EducationField'],
        axis=1, inplace=True)  # 删除掉不重要的特征列和员工号
    OneHot_lis = ['BusinessTravel', 'Department', 'Gender', 'JobLevel',
                  'JobSatisfaction', 'MaritalStatus', 'EnvironmentSatisfaction', 'StockOptionLevel',
                  'RelationshipSatisfaction', 'WorkLifeBalance', 'JobRole']
    ret_data['OverTime'] = data['OverTime'].apply(lambda x: 0 if x == 'No' else 1)

    encoded_data = enc.fit_transform(data[feature][OneHot_lis])
    # print(enc_BusinessTravel.get_feature_names_out())
    data_OneHot = pd.DataFrame(encoded_data, columns=enc.get_feature_names_out())
    ret_data = pd.concat([ret_data, data_OneHot], axis=1)

    ret_data.drop(OneHot_lis, axis=1, inplace=True)
    # print(ret_data)
    # print(ret_data.info())
    # print(ret_data.iloc[:, 1:])
    return ret_data

# 模型导入以及模型评估
def model_test(data_model):
    x = data_model.drop(columns='Attrition')
    y = data_model['Attrition']
    treasfer = StandardScaler()
    x = treasfer.fit_transform(x)

    # es_tree = joblib.load('../model/tree.pkl')
    # y_pre_tree = es_tree.predict(x)
    # print(f"单一决策树正确率{accuracy_score(y, y_pre_tree)}")
    # y_score_tree = es_tree.predict_proba(x)[:, 1]
    # print(f'单一决策树预测AUC：{roc_auc_score(y, y_score_tree)}')
    #
    # es_ada_tree = joblib.load('../model/ada_tree.pkl')
    # y_pre_ada_tree = es_ada_tree.predict(x)
    # print(f"AadBoost集成学习决策树预测正确率{accuracy_score(y, y_pre_ada_tree)}")
    # y_score_ada_tree = es_ada_tree.predict_proba(x)[:, 1]
    # print(f'AadBoost集成学习决策树预测AUC：{roc_auc_score(y, y_score_ada_tree)}')
    #
    # es_ada_log = joblib.load('../model/ada_log.pkl')
    # y_pre_ada_log = es_ada_log.predict(x)
    # print(f"AadBoost集成学习逻辑回归预测正确率{accuracy_score(y, y_pre_ada_log)}")
    #
    logger.info("=========================模型导入中=============================")
    es_log = joblib.load('../model/logist.pkl')
    y_pre_log = es_log.predict(x)
    print(f'精确率：{precision_score(y, y_pre_log, pos_label=0)}')

    print(f'召回率：{recall_score(y, y_pre_log, pos_label=0)}')

    print(f'f1：{f1_score(y, y_pre_log, pos_label=0)}')

    y_pred_proba = es_log.predict_proba(x)[:, 1]
    print(f'逻辑回归预测AUC：{roc_auc_score(y, y_pred_proba)}')
    logger.info(f"LogisticRegression模型在训练集上的AUC：{roc_auc_score(y, y_pred_proba)}")
    #
    # es_xgb = joblib.load('../model/xgb.pkl')
    # class_weight.compute_sample_weight('balanced', y)
    # y_pre_ada_log = es_xgb.predict(x)
    # print(f"xgboost预测正确率{accuracy_score(y, y_pre_ada_log)}")
    # y_score_ada_log = es_xgb.predict_proba(x)[:, 1]
    # print(f'xgboost预测AUC：{roc_auc_score(y, y_score_ada_log)}')

    # y_pre_log = pd.DataFrame(y_pre_log)
    # y_pre_ada_tree = pd.DataFrame(y_pre_ada_tree)
    # y_pre_tree = pd.DataFrame(y_pre_tree)
    # y_pre_ada_log = pd.DataFrame(y_pre_ada_log)
    # y_pre_test = pd.concat([y_pre_log, y_pre_ada_tree, y_pre_tree, y_pre_ada_log], axis=1)
    # # print(y_pre_test)
    # es_KM = KMeans(max_iter=100000, random_state=24)
    # pre_KM = es_KM.fit_predict(y_pre_test)
    # pre_KM = pd.DataFrame(pre_KM)
    # pre_KM = pre_KM.where(pre_KM > 1, 1)
    # print(f"xgboost预测正确率{accuracy_score(y, pre_KM)}")


if __name__ == '__main__':
    data = pd.read_csv('../data/test2.csv')
    data_copy = data.copy(deep=True)
    logger = Logger(root_path='../log', log_name="test_" + datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                    level='debug').get_logger()
    data_model = Data_process(data_copy)
    model_test(data_model)
